/**
 * Copyright (c) 2020 lizebang
 *
 * This software is released under the MIT License.
 * https://opensource.org/licenses/MIT
 */

package jiri

import (
	"os"

	"gitee.com/banggua/ggtsync/cmdutil"
	"gitee.com/banggua/ggtsync/cmdutil/gitutil"
)

type operation interface {
	Run() error
}

type optype bool

var (
	projectOp optype = true
	packageOp optype = false
)

type createOperation struct {
	optype optype
	path   string
	remote string
}

func (co *createOperation) Run() error {
	if co.optype {
		err := os.RemoveAll(co.path)
		if err != nil {
			return err
		}
		return gitutil.CloneMirror("", co.remote, co.path)
	}
	return cmdutil.Run("", "curl", "--location", "--create-dirs", "--output", co.path, co.remote)
}

type deleteOperation struct {
	path string
}

func (do *deleteOperation) Run() error {
	return os.RemoveAll(do.path)
}

type updateOperation struct {
	path   string
	remote string
}

func (uo *updateOperation) Run() error {
	stat, err := os.Stat(uo.path)
	if err != nil {
		if os.IsNotExist(err) {
			return gitutil.CloneMirror("", uo.remote, uo.path)
		}
		return err
	}
	if !stat.IsDir() {
		err = os.Remove(uo.path)
		if err != nil {
			return err
		}
		return gitutil.CloneMirror("", uo.remote, uo.path)
	}
	return gitutil.FetchAll(uo.path, uo.remote)
}
